package org.jeecg.modules.system.util;

import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.model.DepartIdModel;
import org.jeecg.modules.system.model.SysDepartTreeModel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * <P>
 * 对应部门的表,处理并查找树级数据
 * <P>
 *
 * @Author: Steve
 * @Date: 2019-01-22
 */
public class FindsDepartsChildrenUtil {

	//部门树信息-树结构
	//private static List<SysDepartTreeModel> sysDepartTreeList = new ArrayList<SysDepartTreeModel>();

	//部门树id-树结构
    //private static List<DepartIdModel> idList = new ArrayList<>();


    /**
     * queryTreeList的子方法 ====1=====
     * 该方法是s将SysDepart类型的list集合转换成SysDepartTreeModel类型的集合
     */
    public static List<SysDepartTreeModel> wrapTreeDataToTreeList(List<SysDepart> recordList) {
        // 在该方法每请求一次,都要对全局list集合进行一次清理
        //idList.clear();
    	List<DepartIdModel> idList = new ArrayList<DepartIdModel>();
        List<SysDepartTreeModel> records = new ArrayList<>();
        for (int i = 0; i < recordList.size(); i++) {
            SysDepart depart = recordList.get(i);
            records.add(new SysDepartTreeModel(depart));
        }
        List<SysDepartTreeModel> tree = findChildren(records, idList);
        setEmptyChildrenAsNull(tree);
        return tree;
    }

    /**
     * 获取 DepartIdModel
     * @param recordList
     * @return
     */
    public static List<DepartIdModel> wrapTreeDataToDepartIdTreeList(List<SysDepart> recordList) {
        // 在该方法每请求一次,都要对全局list集合进行一次清理
        //idList.clear();
        List<DepartIdModel> idList = new ArrayList<DepartIdModel>();
        List<SysDepartTreeModel> records = new ArrayList<>();
        for (int i = 0; i < recordList.size(); i++) {
            SysDepart depart = recordList.get(i);
            records.add(new SysDepartTreeModel(depart));
        }
        findChildren(records, idList);
        return idList;
    }

    /**
     * queryTreeList的子方法 ====2=====
     * 该方法是找到并封装顶级父类的节点到TreeList集合
     */
    private static List<SysDepartTreeModel> findChildren(List<SysDepartTreeModel> recordList,
                                                         List<DepartIdModel> departIdList) {

        List<SysDepartTreeModel> treeList = new ArrayList<>();
        for (int i = 0; i < recordList.size(); i++) {
            SysDepartTreeModel branch = recordList.get(i);
            if (oConvertUtils.isEmpty(branch.getParentId())) {
                treeList.add(branch);
                DepartIdModel departIdModel = new DepartIdModel().convert(branch);
                departIdList.add(departIdModel);
            }
        }
        getGrandChildren(treeList,recordList,departIdList);

        //idList = departIdList;
        return treeList;
    }

    /**
     * queryTreeList的子方法====3====
     *该方法是找到顶级父类下的所有子节点集合并封装到TreeList集合
     */
    private static void getGrandChildren(List<SysDepartTreeModel> treeList,List<SysDepartTreeModel> recordList,List<DepartIdModel> idList) {

        for (int i = 0; i < treeList.size(); i++) {
            SysDepartTreeModel model = treeList.get(i);
            DepartIdModel idModel = idList.get(i);
            for (int i1 = 0; i1 < recordList.size(); i1++) {
                SysDepartTreeModel m = recordList.get(i1);
                if (m.getParentId()!=null && m.getParentId().equals(model.getId())) {
                    model.getChildren().add(m);
                    DepartIdModel dim = new DepartIdModel().convert(m);
                    idModel.getChildren().add(dim);
                }
            }
            getGrandChildren(treeList.get(i).getChildren(), recordList, idList.get(i).getChildren());
        }

    }

    public static List<SysDepartTreeModel> getTreeList(List<SysDepart> recordList){
        List<SysDepartTreeModel> list = new ArrayList<>();
        LoginUser sysUser = JwtUtil.getLoginUser();
        AtomicReference<String> firstKey = new AtomicReference<>("0");
        recordList.forEach(sysDepart -> {
            //瞎几把写，这里为啥子要屏蔽其他部门嘛，选都选不到了，烦得很
//            if (sysDepart.getId().equalsIgnoreCase(sysUser.getCurrentCompanyId())){
//                firstKey.set(sysDepart.getParentId());
//            }
            list.add(new SysDepartTreeModel(sysDepart));
        });
        //分组
        Map<String, List<SysDepartTreeModel>> collect = list.stream().collect(Collectors.groupingBy(SysDepartTreeModel::getParentId));
        //树形结构 肯定有一个根部，我的这个根部的就是parentId.euqal("0"),而且只有一个就get（"0"）
        SysDepartTreeModel sysDepartTreeModel = collect.get(firstKey.get()).get(0);
        //拼接数据
        forEach(collect, sysDepartTreeModel);
        return new ArrayList<SysDepartTreeModel>(){{add(sysDepartTreeModel);}};
    }

    private static void forEach(Map<String, List<SysDepartTreeModel>> collect, SysDepartTreeModel SysDepartTreeModel) {
        List<SysDepartTreeModel> SysDepartTreeModels = collect.get(SysDepartTreeModel.getId());
        if(collect.get(SysDepartTreeModel.getId())!=null){
            //排序
            SysDepartTreeModels.sort((u1, u2) -> u1.getDepartOrder().compareTo(u2.getDepartOrder()));
//            SysDepartTreeModels.stream().sorted(Comparator.comparing(SysDepartTreeModel::getDepartOrder)).collect(Collectors.toList());
            SysDepartTreeModel.setChildren(SysDepartTreeModels);
            SysDepartTreeModel.getChildren().forEach(t->{
                forEach(collect,t);
                if (t.getChildren() == null || t.getChildren().size() == 0){
                    t.setChildren(null);
                    t.setLeaf(true);
                }
            });
        }
    }

    public static void getChildrenId(List<DepartIdModel> idModelList, List<SysDepartTreeModel> treeModelList) {
        if (treeModelList != null && treeModelList.size() > 0) {
            treeModelList.forEach(m->{
                DepartIdModel model = new DepartIdModel().convert(m);
                List<DepartIdModel> modelList = new ArrayList<>();
                getChildrenId(modelList, m.getChildren());
                model.setChildren(modelList);
                idModelList.add(model);
            });
        }
    }

    /**
     * queryTreeList的子方法 ====4====
     * 该方法是将子节点为空的List集合设置为Null值
     */
    private static void setEmptyChildrenAsNull(List<SysDepartTreeModel> treeList) {

        for (int i = 0; i < treeList.size(); i++) {
            SysDepartTreeModel model = treeList.get(i);
            if (model.getChildren().size() == 0) {
                model.setChildren(null);
                model.setLeaf(true);
            }else{
                setEmptyChildrenAsNull(model.getChildren());
                model.setLeaf(false);
            }
        }
        // sysDepartTreeList = treeList;
    }
}
